package com.its.us.web.config.filter.web;

import com.its.us.web.entity.sys.User;
import com.its.us.web.utils.*;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: master
 * @Date: 2020/10/29 12:20
 * @Version: 1.0
 */
@Deprecated
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    public TokenLoginFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    private AuthenticationManager authenticationManager;
    private static JwtTokenUtil jwtTokenUtil;


    static {
        jwtTokenUtil = SpringContext.getBean(JwtTokenUtil.class);
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            String username = this.obtainUsername(request).trim();
            String password = this.obtainPassword(request).trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            this.setDetails(request, authRequest);
            return authenticationManager.authenticate(authRequest);
        } catch (Exception e) {
            try {
                Map<String, Object> map = new HashMap<>();
                map.put("msg", "用户名或密码错误");
                map.put("code", 201);
                ResponseUtil.out(201, response, JsonUtil.toJson(map));
            } catch (Exception outEx) {
                outEx.printStackTrace();
            }
            logger.error("用户名或密码错误：", e);
            throw new RuntimeException(e);
        }
    }

    public void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) {
        User user = (User) authResult.getPrincipal();
//        user.setId(user.getId());
//        user.setUsername(user.getUsername());
//        user.setAuthorities((List<GrantedAuthority>) user.getAuthorities());
        String password = request.getParameter(ConstantsUtil.UserParam.PASS_WORD);
        //TODO，将username和password被获得后封装到UsernamePasswordAuthenticationToken
        Authentication token = new UsernamePasswordAuthenticationToken(user.getUsername(), password, authResult.getAuthorities());
        //TODO，token被传递给AuthenticationManager进行验证
        Authentication authentication = authenticationManager.authenticate(token);

        //将生成的authentication放入容器中，生成安全的上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成token
        final String realToken = jwtTokenUtil.generateToken(user);
        //response.addHeader("Authorization", "Bearer " + realToken);
        response.addHeader(ConstantsUtil.Token.TOKEN_NAME, "web");
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("code", 200);
            map.put("sub", user.getUsername());
            map.put("msg", "登录成功.");
            map.put("token", realToken);
            ResponseUtil.out(200, response, JsonUtil.toJson(map));

        } catch (Exception outEx) {
            outEx.printStackTrace();
        }
    }
}
